package com.chujie.chat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerMain {
    private static final Logger logger = LoggerFactory.getLogger(ServerMain.class);

    private int port;

    public ServerMain(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        int port=8989;
        if (args.length>0){
            port=Integer.parseInt(args[0]);
        }
        new ServerMain(port).run();
    }

    public void run() {
        logger.info("开始启动--------------------------");
        EventLoopGroup acceptor = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.option(ChannelOption.SO_BACKLOG, 2048);
        bootstrap.group(acceptor, worker);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.childHandler(new ServerIniterHandler());
        try {
            Channel channel = bootstrap.bind(port).sync().channel();
            System.out.println("server strart running in port:" + port);
            logger.info("服务启动成功--------------------------");
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            logger.info("服务停止--------------------------");
            acceptor.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}